import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @description: 15. 三数之和
* @author hewei
* @date 2022/9/21 14:26
* @version 1.0
*/

public class ThreeSum {

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < n - 2; i++) {
            int target = -nums[i];
            int l = i + 1;
            int r = n - 1;
            while (l < r) {
                if (nums[l] + nums[r] > target) {
                    --r;
                } else if (nums[l] + nums[r] < target) {
                    ++l;
                } else {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[l]);
                    list.add(nums[r]);
                    ans.add(list);
                    while (l + 1 < r && nums[l + 1] == nums[l]) ++l;
                    while (r - 1 > l && nums[r - 1] == nums[r]) --r;
                    ++l;
                    --r;
                }
            }
            while (i + 1 < n - 2 && nums[i + 1] == nums[i]) ++i;
        }
        return ans;
    }
}
